const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const groupsCollection = db.collection('groups')

// 随机分组算法
function randomizeGroups(totalMembers, groupCount) {
  // 创建成员索引数组
  let members = Array.from({length: totalMembers}, (_, i) => i)
  
  // Fisher-Yates 洗牌算法
  for (let i = members.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [members[i], members[j]] = [members[j], members[i]]
  }
  
  // 计算每组的基本人数和余数
  const baseSize = Math.floor(totalMembers / groupCount)
  const remainder = totalMembers % groupCount
  
  // 分配成员到各组
  const groups = []
  let currentIndex = 0
  
  for (let i = 0; i < groupCount; i++) {
    const groupSize = i < remainder ? baseSize + 1 : baseSize
    groups.push(members.slice(currentIndex, currentIndex + groupSize))
    currentIndex += groupSize
  }
  
  return groups
}

exports.main = async (event, context) => {
  const { totalMembers, groupCount, groupNames } = event
  const wxContext = cloud.getWXContext()
  
  try {
    // 创建分组计划
    const plan = {
      _id: `plan_${Date.now()}`,
      creator: wxContext.OPENID,
      totalMembers,
      groupCount,
      groupNames,
      createTime: new Date(),
      status: 'pending',
      members: [],
      groups: randomizeGroups(totalMembers, groupCount)
    }
    
    // 保存到数据库
    await groupsCollection.add({
      data: plan
    })
    
    return {
      success: true,
      data: plan
    }
  } catch (err) {
    console.error(err)
    return {
      success: false,
      error: err
    }
  }
} 